package com.wannengbang.cloudleader.mine;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseFragment;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AgentLevelBean;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.UpDateNameEvent;
import com.wannengbang.cloudleader.homepage.IncomeStatisticsActivity;
import com.wannengbang.cloudleader.homepage.ShareLevelActivity;
import com.wannengbang.cloudleader.homepage.TeamQuotaActivity;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.login.LoginActivity;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.utils.CallPhoneUtil;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.VersionUtil;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;
import com.wannengbang.cloudleader.widget.ViewLoading;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import ch.ielse.view.SwitchView;

/**
 * 我的
 */
public class MineFragment extends BaseFragment {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.switchview)
    SwitchView switchview;
    @BindView(R.id.ll_bg_launch)
    LinearLayout llBgLaunch;
    @BindView(R.id.ll_feekback)
    LinearLayout llFeekback;
    @BindView(R.id.ll_about_us)
    LinearLayout llAboutUs;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.ll_outLogin)
    LinearLayout llOutLogin;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_start_vname)
    TextView tvStartVname;
    @BindView(R.id.tv_start_v)
    TextView tvStartV;
    @BindView(R.id.tv_start_v2)
    TextView tvStartV2;
    @BindView(R.id.ll_by_my_order)
    LinearLayout llByMyOrder;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ll_income_statistics)
    LinearLayout llIncomeStatistics;
    @BindView(R.id.ll_share_level)
    RelativeLayout llShareLevel;
    @BindView(R.id.ll_team_quota)
    LinearLayout llTeamQuota;
    @BindView(R.id.tv_telphone)
    TextView tvTelphone;
    @BindView(R.id.ll_kefu_mobile)
    LinearLayout llKefuMobile;

    @BindView(R.id.tv_ck)
    TextView tv_ck;
    @BindView(R.id.tv_yyzx)
    TextView tv_yyzx;
    @BindView(R.id.tv_ds)
    TextView tv_ds;


    private Unbinder unbinder;
    private UserInfoBean userInfoBean;
    private CommonNoTitleDialog.Builder dialogBuild;
    private IHomePageModel homePageModel;
    private int agency;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        registerEventBus();
        return view;
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();
    }

    public void initView() {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null) {
            tvName.setText(userInfoBean.getData().getName());
        }
        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null) {

            int maker = userInfoBean.getData().getMaker();
            int hb_operation_type = userInfoBean.getData().getHb_operation_type();
            int star_count = userInfoBean.getData().getStar_count();
            agency = userInfoBean.getData().getAgency();



            if (1==maker){
                tv_ck.setVisibility(View.VISIBLE);
            }else if (2==maker){
                tv_ck.setVisibility(View.GONE);
            }
            if (star_count>0){
                tv_ds.setVisibility(View.VISIBLE);
            }else {
                tv_ds.setVisibility(View.GONE);
            }

            if (1==hb_operation_type){
                tv_yyzx.setVisibility(View.VISIBLE);
            }else if (2==hb_operation_type){
                tv_yyzx.setVisibility(View.GONE);
            }


        }

        homePageModel = new HomePageModelImpl();
        tvVersion.setText("V" + VersionUtil.packageName(mActivity));
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        tvName.setText(userInfoBean.getData().getName());

        //星级
        if (userInfoBean.getData().getStar_count() > 0) {
            tvStartV2.setText("您的当前星级：" + userInfoBean.getData().getStar_count() + "星荣誉董事");
        } else {
            tvStartV2.setText("您的当前星级：" + userInfoBean.getData().getStar_count() + "星暂无等级");
        }
        if ("true".equals(SPManager.getInstance().getSpeechSwitch())) {
            switchview.setOpened(true);
        } else {
            switchview.setOpened(false);
        }
        switchview.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn(SwitchView view) {
                switchview.setOpened(true);
                SPManager.getInstance().saveSpeechSwitch("true");
            }

            @Override
            public void toggleToOff(SwitchView view) {
                switchview.setOpened(false);
                SPManager.getInstance().saveSpeechSwitch("false");
            }
        });
    }

    public void requestAgentGetLevel() {
        homePageModel.requestAgentGetLevel(new DataCallBack<AgentLevelBean>() {
            @Override
            public void onSuccessful(AgentLevelBean bean) {
                tvEndTime.setText("特权有效期至：" + bean.getData().getEnd_date());
                tvStartV.setText("V" + bean.getData().getLevel());
                tvStartVname.setText("分润等级");
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 用户信息
     */
    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                if (bean.getData().getStar_count() > 0) {
                    tvStartV2.setText("您的当前星级：" + bean.getData().getStar_count() + "星荣誉董事");
                } else {
                    tvStartV2.setText("您的当前星级：" + bean.getData().getStar_count() + "星暂无等级");
                }

                if ("17329409714".equals(bean.getData().getMobile()) || "13403854628".equals(bean.getData().getMobile())) {
                    llKefuMobile.setVisibility(View.VISIBLE);
                } else {
                    llKefuMobile.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void onUpDateNameEvent(UpDateNameEvent event) {
//        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
//        if (userInfoBean != null) {
//            tvName.setText(userInfoBean.getData().getName());
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestAgentGetLevel();
        requestUserInfo();
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestAgentGetLevel();
            requestUserInfo();
        }
    }

    @OnClick({R.id.ll_kefu_mobile, R.id.iv_header, R.id.tv_name, R.id.ll_by_my_order, R.id.ll_income_statistics, R.id.ll_team_quota, R.id.ll_bg_launch, R.id.ll_feekback, R.id.ll_about_us, R.id.ll_setting, R.id.ll_outLogin, R.id.ll_share_level})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_header:
            case R.id.tv_name:
                if (userInfoBean == null) {
                    return;
                }
                Intent intent = new Intent(mActivity, UpdateNameActivity.class);
                intent.putExtra("name", userInfoBean.getData().getName());
                startActivity(intent);
                break;
            case R.id.ll_by_my_order:
                skipToActivity(ByMyOrderListActivity.class);
                break;
            case R.id.ll_income_statistics:
                skipToActivity(IncomeStatisticsActivity.class);
                break;
            case R.id.ll_team_quota:
                skipToActivity(TeamQuotaActivity.class);
                break;
            case R.id.ll_bg_launch:
                skipToActivity(LaunchManageActivity.class);
                break;
            case R.id.ll_feekback:
                skipToActivity(FeedBackActivity.class);
                break;
            case R.id.ll_about_us:
                skipToActivity(AboutUsActivity.class);
                break;
            case R.id.ll_setting:
                skipToActivity(SettingActivity.class);
                break;
            case R.id.ll_share_level:
                skipToActivity(ShareLevelActivity.class);
                break;
            case R.id.ll_outLogin:
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("是否退出登录?");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    outLogin();
                });
                dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
            case R.id.ll_kefu_mobile:
                String tel = tvTelphone.getText().toString();
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("是否拨打" + tel);
                dialogBuild.setPositiveButton("是", v -> {
                    dialogBuild.dismiss();
                    CallPhoneUtil.callPhone(mActivity, tel);
                });
                dialogBuild.setNegativeButton("否", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
        }
    }

    /**
     * 退出登录
     */
    public void outLogin() {
        ViewLoading.showProgress(mActivity);
        //解绑DeviceId
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        new MineModelImpl().requestUnBindDeviceId(pushService.getDeviceId(), new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
        //退出登录
        new MineModelImpl().requestLoginOut(userInfoBean.getData().getId() + "", new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
        SPManager.getInstance().logOffRemove();
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
        mActivity.finish();
    }

}
